package com.hopu.mybatis.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * MyBatis工具类
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory = null;
    //保存SqlSession的线程布局变量
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    static{
        //初始化工厂
        factory = new SqlSessionFactoryBuilder().build(
                MyBatisUtil.class.getClassLoader().getResourceAsStream("mybatis.xml"));
    }

    /**
     * 获得当前线程中的SqlSession
     * @return
     */
    public static SqlSession getSession(){
        //读取当前线程中的SQLSession
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            //如果为空，就创建SqlSession
            sqlSession = factory.openSession();
            //保存到当前线程中
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 关闭SqlSession
     */
    public static void closeSession(){
        //读取当前线程中的SQLSession
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            //如果不为空，就关闭SqlSession
            sqlSession.close();
            sqlSession = null;
            //线程局部变量中的SqlSession设置为null
            threadLocal.set(null);
        }
    }
}
